package com.peycard.business;

import java.util.Date;
import java.util.Random;

import javax.ejb.Stateless;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.peycard.business.local.DateServiceLocal;
import com.peycard.business.local.TokenServiceLocal;
import com.peycard.persistence.PersistenceException;
import com.peycard.persistence.dao.local.TokenPortalDAOLocal;
import com.peycard.persistence.entities.Adsysuser;
import com.peycard.persistence.entities.TokenPortal;

/**
 * Session Bean implementation class TokenService
 */
@Stateless
public class TokenService implements TokenServiceLocal {

	public static String NUMEROS = "0123456789";
    public static String MAYUSCULAS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static String MINUSCULAS = "abcdefghijklmnopqrstuvwxyz";
    private TokenPortalDAOLocal tokenDAO;
    private DateServiceLocal dateService;
	
    public TokenService() {		
		try {
			Context ctx = new InitialContext();			
			tokenDAO = (TokenPortalDAOLocal) ctx
			.lookup("ejblocal:com.peycard.persistence.dao.local.TokenPortalDAOLocal");
			dateService = (DateServiceLocal) ctx
			.lookup("ejblocal:com.peycard.business.local.DateServiceLocal");
		} catch (NamingException nex) {			
			throw new RuntimeException(
					"NO SE PUDO OBTENER REFERENCIA AL OBJETO ");
		}
	}	
    

    @Override
    public String generateToken()  {
        StringBuilder randomString = new StringBuilder();
        Random random = new Random();
        boolean alphaType = true;
        int j;

        for (int i = 0; i <= 25; ++i) {
            j = (random.nextInt(25) + (alphaType == true ? 65 : 97));
            randomString.append((char) j);
            alphaType = !alphaType;
        }
        return randomString.toString();
    }

    @Override
    public String generatePassword(){
        String key = MINUSCULAS + NUMEROS + MAYUSCULAS;
        int length = 15;
        String pswd = "";

        for (int i = 0; i < length; i++) {
            pswd += (key.charAt((int) (Math.random() * key.length())));
        }

        return pswd;
    }


	@Override
	public void saveToken(Adsysuser user,String newToken) {
		try {
			TokenPortal t=tokenDAO.getToken(user.getIdAdminSysUser());			
			t.setAddDate(dateService.getDate());
			t.setExpirationDate(dateService.generateDateExpirate());
			t.setToken(newToken);
			tokenDAO.update(t);
		} catch (PersistenceException e) {
			throw new RuntimeException(
				"No se pudo actualizar token");
		}
	}

	@Override
	public boolean validateToken(Adsysuser user,String tokenReq) {
		try {
			TokenPortal t=tokenDAO.getToken(user.getIdAdminSysUser());
			if(t.getToken().equals(tokenReq)){
				Date fechaExp = t.getExpirationDate();
	            Date fechaAct = dateService.getDate();
	            if (fechaExp.compareTo(fechaAct) > 0) {
	                return true;
	            }else{
	            	return false;
	            }
			}else{
				return false;
			}
		} catch (PersistenceException e) {
			throw new RuntimeException(
				"No se pudo actualizar token");
		}		
	}
}
